package com.ifuncat.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifuncat.gulimall.common.constant.ProductConstant;
import com.ifuncat.gulimall.common.utils.PageUtils;
import com.ifuncat.gulimall.common.utils.Query;
import com.ifuncat.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.ifuncat.gulimall.product.dao.AttrDao;
import com.ifuncat.gulimall.product.dao.AttrGroupDao;
import com.ifuncat.gulimall.product.dao.CategoryDao;
import com.ifuncat.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.ifuncat.gulimall.product.entity.AttrEntity;
import com.ifuncat.gulimall.product.entity.AttrGroupEntity;
import com.ifuncat.gulimall.product.entity.CategoryEntity;
import com.ifuncat.gulimall.product.service.AttrService;
import com.ifuncat.gulimall.product.service.CategoryService;
import com.ifuncat.gulimall.product.vo.AttrGroupRelationVo;
import com.ifuncat.gulimall.product.vo.AttrRespVo;
import com.ifuncat.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //1.保存基本数据
        this.save(attrEntity); //保存成功后,会将生成的主键Id返回给attrEntity
        //2.基本属性才需要保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId()); //注意使用attrEntity,attrId不为空
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (0 != catelogId) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        //设置分组,分类名
        List<AttrRespVo> voList = setCatelogAndGroup(page.getRecords());

        //重新组装分页对象
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(voList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        //基本信息
        BeanUtils.copyProperties(attrEntity, respVo);
        //设置分组,分类
        setAttrGroup(respVo);
        setCategory(respVo);

        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //更新基本数据
        this.updateById(attrEntity);
        //更新属性分组,如果之前不存在,则新增这个分组
        updateAttrGroup(attr);
    }

    @Override
    public PageUtils querySaleAttrPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (0 != catelogId) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        List<AttrRespVo> voList = setCatelog(page.getRecords()); //设置分类

        //重新组装分页对象
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(voList);
        return pageUtils;
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> attrIdList = relationList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(attrIdList)) {
            return new ArrayList<>();
        } else {
            return new ArrayList<>(this.listByIds(attrIdList));
        }
    }

    @Override
    public void deleteAttrRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.stream(vos).map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);
    }

    /***
     * 获得某一分组下的没有关联的所有属性
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrGroupId, Map<String, Object> params) {
        //1.当前分组只能关联自己所属的分类中的所有属性,获取当前分类的id
        Long catelogId = attrGroupDao.selectById(attrGroupId).getCatelogId();
        //2.只能关联还未与其他分组进行关联的属性,即在关联表中不存在的记录
        //2.1获得该分类下的所有分组
        List<Long> attrGroupIdList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId)).stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        //2.2获得已关联的所有属性
        List<Long> attrIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(attrGroupIdList)) {
            attrIdList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIdList)).stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        }
        //2.3 移除已经关联的属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(attrIdList)) {
            queryWrapper.notIn("attr_id", attrIdList);
        }
        String key = (String) params.get("key"); //判断是否存在模糊查询
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(i -> i.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 设置分类
     */
    private List<AttrRespVo> setCatelog(List<AttrEntity> entityList) {
        return entityList.stream().map(entity -> {
            AttrRespVo vo = new AttrRespVo();
            BeanUtils.copyProperties(entity, vo);
            //设置分类名
            CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
            if (null != categoryEntity) {
                vo.setCatelogName(categoryEntity.getName());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 更新属性分组,如果之前不存在,则新增这个分组
     */
    private void updateAttrGroup(AttrVo attr) {
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attr.getAttrId());

        Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        if (count > 0) {
            attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        } else {
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    /**
     * 设置分组
     */
    private void setAttrGroup(AttrRespVo respVo) {
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", respVo.getAttrId()));
        if (null == relationEntity || null == relationEntity.getAttrGroupId()) return;
        respVo.setAttrGroupId(relationEntity.getAttrGroupId());
        AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
        if (null != groupEntity) {
            respVo.setGroupName(groupEntity.getAttrGroupName());
        }
    }

    /**
     * 设置分类
     */
    private void setCategory(AttrRespVo respVo) {
        Long[] catelogPath = categoryService.findCatelogPath(respVo.getCatelogId());
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(respVo.getCatelogId());
        if (null != categoryEntity) {
            respVo.setCatelogName(categoryEntity.getName());
        }
    }

    private List<AttrRespVo> setCatelogAndGroup(List<AttrEntity> entityList) {
        return entityList.stream().map(entity -> {
            AttrRespVo vo = new AttrRespVo();
            BeanUtils.copyProperties(entity, vo);

            //设置分组,分类名
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId()));
            if (null != relationEntity) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                vo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
            if (null != categoryEntity) {
                vo.setCatelogName(categoryEntity.getName());
            }
            return vo;
        }).collect(Collectors.toList());
    }

}